/**
 * PLM项目Store配置入口
 * 统一导出所有Store模块
 */

// 导入MobX绑定
const { createStoreBindings } = require('mobx-miniprogram-bindings');

// 安全导入所有Store模块
const plmStore = require('../store/plm_store');
const projectStore = require('../store/plm_project_store_wrapper');

// 导入研发相关Store
let researchProjectStore = {};
try {
  researchProjectStore = require('../store/modules/research/project_store');
} catch (e) {
  console.warn('导入模块失败: ../store/modules/research/project_store，使用空实现', e);
}

let researchStateStore = {};
try {
  researchStateStore = require('../store/modules/research/state_machine/store');
} catch (e) {
  console.warn('导入模块失败: ../store/modules/research/state_machine/store，使用空实现', e);
}

// 用户Store
const userStore = {
  user: { role: 'admin' },
  isLoggedIn: true
};

// 备用Store实现 - 当主Store加载失败时将使用它
const fallbackStore = {
  projectList: [],
  loading: false,
  error: null,
  pagination: { page: 1, size: 20, total: 0, hasMore: false },
  filters: { search: '', status: 'all', sortType: 'recent' },
  getProjectList: async (params) => {
    console.log('调用备用getProjectList, 参数:', params);
    return { list: [], total: 0 };
  },
  setFilters: (filters) => {
    console.log('设置过滤器:', filters);
  },
  reset: () => {
    console.log('重置Store');
  }
};

// 确保plmProjectStore包含基础方法
// 包装projectStore，添加缺失的方法
const plmProjectStore = {
  ...projectStore,
  
  // 初始化字段，避免undefined错误
  projects: [],
  quickAccessList: [],
  filter: {},
  filteredProjects: [],
  projectCount: 0,
  
  // 确保reset方法存在
  reset: function() {
    console.log('调用plmProjectStore.reset()');
    if (projectStore.clearAll) {
      projectStore.clearAll();
    } else if (projectStore.reset) {
      projectStore.reset();
    }
  },
  
  // 确保loadProjects方法存在（项目列表页面需要此方法）
  loadProjects: async function(forceRefresh = false) {
    console.log('调用plmProjectStore.loadProjects()');
    try {
      let result;
      
      if (projectStore.loadProjectList) {
        // 尝试使用loadProjectList方法
        try {
          result = await projectStore.loadProjectList({ 
            forceRefresh, 
            // 如果是强制刷新，也强制从云端获取
            forceCloud: forceRefresh 
          });
        } catch (error) {
          console.warn('loadProjectList方法失败:', error);
          // 继续尝试其他方法
        }
      }
      
      // 如果上面的方法失败或不存在，尝试getProjectList
      if (!result && projectStore.getProjectList) {
        try {
          result = await projectStore.getProjectList({
            forceRefresh, 
            // 如果是强制刷新，也强制从云端获取
            forceCloud: forceRefresh
          });
        } catch (error) {
          console.warn('getProjectList方法失败:', error);
          // 使用备用数据
        }
      }
      
      // 安全处理结果
      if (!result || typeof result !== 'object') {
        console.warn('项目列表数据格式不正确, 使用空数组');
        result = { list: [], total: 0 };
      }
      
      // 确保结果包含list属性
      if (!result.list || !Array.isArray(result.list)) {
        console.warn('项目列表数据缺少list字段或格式不正确, 使用空数组');
        result.list = [];
      }
      
      // 确保结果包含total属性
      if (typeof result.total !== 'number') {
        console.warn('项目列表数据缺少total字段, 使用list长度');
        result.total = result.list.length;
      }
      
      // 确保projects字段存在
      this.projects = result.list;
      
      // 确保projectCount字段存在
      this.projectCount = result.total;
      
      // 确保filteredProjects字段存在
      this.filteredProjects = result.list;
      
      // 详细记录获取到的项目列表
      console.log('plmProjectStore.loadProjects 成功加载项目列表, 数量:', result.list.length);
      console.log('获取到的前三个项目:', result.list.slice(0, 3).map(p => ({ _id: p._id, model: p.model })));
      
      return result;
    } catch (error) {
      console.error('加载项目列表失败:', error);
      
      // 确保关键字段有默认值
      this.projects = this.projects || [];
      this.projectCount = this.projectCount || 0;
      this.filteredProjects = this.filteredProjects || [];
      
      // 返回安全的默认值
      return { 
        list: [], 
        total: 0,
        page: 1,
        size: 20
      };
    }
  }
};

// 创建研发状态机Store的模拟实现（当正常导入失败时使用）
const researchStateMachineMock = {
  currentRole: null,
  availableEvents: [],
  requiredDocs: [],
  
  // 模拟状态机功能
  computeAvailableEvents: (project, userInfo) => {
    console.log('模拟计算可用事件', project?.status);
    researchStateMachineMock.availableEvents = [
      { id: 1, name: '提交评审' },
      { id: 2, name: '退回修改' }
    ];
    return researchStateMachineMock.availableEvents;
  },
  
  getStatusName: (status) => {
    const stateMap = {
      1: '开发中',
      2: '评审中',
      3: '测试中',
      4: '已完成',
      99: '已取消'
    };
    return stateMap[status] || '未知状态';
  },
  
  getTargetStateByEvent: (eventId) => {
    const stateMap = {
      1: { name: '评审中', subName: '待评审' },
      2: { name: '开发中', subName: '退回修改' }
    };
    return stateMap[eventId] || { name: '未知状态', subName: '' };
  }
};

// 确保researchStateMachineStore始终可用
// 首先尝试使用researchStateStore，如果不可用则使用模拟实现
let researchStateMachineStore;
try {
  if (researchStateStore && typeof researchStateStore.getStatusName === 'function') {
    // 如果researchStateStore存在并且格式正确，使用它
    console.log('使用真实的research状态机实现');
    researchStateMachineStore = researchStateStore;
  } else {
    // 否则使用模拟实现
    console.log('使用研发状态机模拟实现');
    researchStateMachineStore = researchStateMachineMock;
  }
} catch (e) {
  console.warn('获取研发状态机Store失败，使用模拟实现', e);
  researchStateMachineStore = researchStateMachineMock;
}

// 合并Store配置
const storeConfig = {
  // MobX绑定
  createStoreBindings,
  
  // 导出项目内部实现的Store
  plmStore,
  projectStore,
  plmProjectStore, // 使用包装过的plmProjectStore
  researchProjectStore,
  researchStateStore,
  
  // 导出研发状态机Store
  researchStateMachineStore,
  
  // 用户Store
  userStore,
  
  // 备用Store，在外部可手动应用
  fallbackStore
};

// 导出store配置
module.exports = storeConfig;